package org.dromara.system.service.impl;

import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.BeanUtils;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.api.model.LoginUser;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.PayGroupTypeQueryBo;
import org.dromara.system.domain.vo.*;
import org.dromara.system.mapper.PayAppMapper;
import org.dromara.system.mapper.PayGroupTypeMapper;
import org.dromara.system.service.IPayGroupTypeService;
import org.dromara.system.utils.ConversionUtils;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.PayLinkBo;
import org.dromara.system.mapper.PayLinkMapper;
import org.dromara.system.service.IPayLinkService;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 支付链接Service业务层处理
 *
 * @author Gavino
 * @date 2024-11-01
 */
@RequiredArgsConstructor
@Service
public class PayLinkServiceImpl implements IPayLinkService {

    private final PayLinkMapper baseMapper;
    private final PayAppMapper payAppMapper;
    private final PayGroupTypeMapper payGroupTypeMapper;
    private final IPayGroupTypeService payGroupTypeService;

    @Override
    public R<PayLinkOutVo> getCodeInfo(String code) {
        MPJLambdaWrapper<PayLink> query = new MPJLambdaWrapper<>();
        query.leftJoin(PayApp.class, PayApp::getAppId, PayLink::getAppId);
        query.selectAll(PayLink.class);
        query.select(PayApp::getNeedMail);
        query.select(PayApp::getGoodsType);
        query.eq(PayLink::getCode, code);
        PayLinkOutVo vo = baseMapper.selectJoinOne(PayLinkOutVo.class, query);
        if(vo == null) {
            return R.fail("link not exist");
        }

        if(vo.getStatus() !=  1) {
            //链接不可用
            return R.fail("link not available");
        }
        if(vo.getExpireTime()!= null && vo.getExpireTime().before(new Date())) {
            //链接已过期
            return R.fail("link expire time");
        }
        vo.setStatus(null);
        vo.setExpireTime(null);

        PayApp app = payAppMapper.selectById(vo.getAppId());
        if (app == null) {
            return R.fail("app not exist");
        }

         //获取应用配置的支付平台
        PayGroupTypeQueryBo pbo = new PayGroupTypeQueryBo(vo.getTotal().toPlainString(), vo.getCurrency(), vo.getCountry(), null);
        R<List<PayTypeOutVo>> r = payGroupTypeService.selectPayGroupType(app.getGroupId(), null, pbo);

        if(R.isError(r)) {
            return R.fail(r.getMsg());
        }
        vo.setPayType(r.getData());

        return R.ok(vo);
    }

    @Override
    public PayLinkVo selectByCode(String code) {
        MPJLambdaWrapper<PayLink> query = new MPJLambdaWrapper<>();
        query.leftJoin(PayApp.class, PayApp::getAppId, PayLink::getAppId);
        query.selectAll(PayLink.class);
        query.select(PayApp::getNeedMail);
        query.select(PayApp::getGoodsType);
        query.eq(PayLink::getCode, code);
        return baseMapper.selectJoinOne(PayLinkVo.class, query);
    }

    /**
     * 查询支付链接
     *
     * @param linkId 主键
     * @return 支付链接
     */
    @Override
    public PayLinkVo queryById(Long linkId){
        PayLinkVo vo = baseMapper.selectVoById(linkId);
        PayApp app = payAppMapper.selectById(vo.getAppId());
        vo.setGoodsType(app.getGoodsType());
        vo.setNeedMail(app.getNeedMail());
        return vo;
    }

    /**
     * 分页查询支付链接列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 支付链接分页列表
     */
    @Override
    public TableDataInfo<PayLinkVo> queryPageList(PayLinkBo bo, PageQuery pageQuery) {
        MPJLambdaWrapper<PayLink> query = buildQueryWrapper(bo);
        query.leftJoin(PayApp.class, PayApp::getAppId, PayLink::getAppId);
        query.selectAll(PayLink.class);
        query.select(PayApp::getNeedMail);
        query.select(PayApp::getGoodsType);
        query.orderByDesc(PayLink::getLinkId);
        Page<PayLinkVo> result = baseMapper.selectJoinPage(pageQuery.build(), PayLinkVo.class, query);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的支付链接列表
     *
     * @param bo 查询条件
     * @return 支付链接列表
     */
    @Override
    public List<PayLinkVo> queryList(PayLinkBo bo) {
        MPJLambdaWrapper<PayLink> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private MPJLambdaWrapper<PayLink> buildQueryWrapper(PayLinkBo bo) {
        MPJLambdaWrapper<PayLink> lqw = new MPJLambdaWrapper<>(PayLink.class);
        if (LoginHelper.isAgent()) {
            bo.setAgentId(LoginHelper.getUserId());
        }
        if (LoginHelper.isClient()) {
            bo.setCreateId(LoginHelper.getUserId());
        }

        lqw.eq(StringUtils.isNotBlank(bo.getCode()), PayLink::getCode, bo.getCode());
        lqw.eq(bo.getAppId() != null, PayLink::getAppId, bo.getAppId());
        lqw.eq(StringUtils.isNotBlank(bo.getCountry()), PayLink::getCountry, bo.getCountry());
        lqw.eq(bo.getStatus() != null, PayLink::getStatus, bo.getStatus());
        lqw.eq(bo.getCreateId() != null, PayLink::getCreateId, bo.getCreateId());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateName()), PayLink::getCreateName, bo.getCreateName());
        lqw.eq(bo.getAgentId() != null, PayLink::getAgentId, bo.getAgentId());
        lqw.eq(bo.getIsDelete() != null, PayLink::getIsDelete, bo.getIsDelete());
        lqw.eq(bo.getExpire() != null, PayLink::getExpire, bo.getExpire());

        //处理日期范围查询
        Map<String, Object> params = bo.getParams();
        lqw.between(params.get("beginExpireTime") != null && params.get("endExpireTime") != null,
            PayLink::getExpireTime, params.get("beginExpireTime"), params.get("endExpireTime"));
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            PayLink::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));

        return lqw;
    }

    /**
     * 新增支付链接
     *
     * @param bo 支付链接
     * @return 是否新增成功
     */
    @Override
    public R<?> insertByBo(PayLinkBo bo) {
        PayLink add = BeanUtils.copy(bo, PayLink.class);

        LoginUser user = LoginHelper.getLoginUser();

        if (!LoginHelper.isSuperAdmin() && !LoginHelper.isClient()) {
            return R.fail("未授权");
        }
        if (Objects.equals(add.getExpire(), 1) && bo.getTime() > 0) {
            add.setExpireTime(Date.from(LocalDateTime.now().plusHours((long) bo.getTime()).atZone(ZoneId.systemDefault()).toInstant()));
        }

        add.setCode(ConversionUtils.generateShortCode(System.currentTimeMillis() + "", 8));
        add.setCreateId(LoginHelper.getUserId());
        add.setCreateName(LoginHelper.getUsername());
        add.setAgentId(user.getAgentId());
        add.setAgentName(user.getAgentName());
        add.setStatus(1);
        add.setIsDelete(0);
        add.setCreateTime(DateUtils.getNowDate());
        baseMapper.insert(add);

        return R.ok();
    }

    /**
     * 修改支付链接
     *
     * @param bo 支付链接
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(PayLinkBo bo) {
        PayLink update = MapstructUtils.convert(bo, PayLink.class);
        update.setUpdateId(LoginHelper.getUserId());
        update.setUpdateName(LoginHelper.getUsername());
        update.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 校验并批量删除支付链接信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        LambdaQueryWrapper<PayLink> query = new LambdaQueryWrapper<>();
        query.in(PayLink::getLinkId, ids);
        if (LoginHelper.isAgent()) {
            query.eq(PayLink::getAgentId, LoginHelper.getUserId());
        }
        if (LoginHelper.isClient()) {
            query.eq(PayLink::getCreateId, LoginHelper.getUserId());
        }
        return baseMapper.delete(query) > 0;
    }
}
